#include "Acceptor.h"

Acceptor::Acceptor(const string & ip, unsigned short port)
:_sock()
,_addr(ip,port)
{}

Acceptor::~Acceptor(){

}

void Acceptor::ready(){
    setReuseAddr();
    setReusePort();
    bind();
    listen();
}

int Acceptor::accept(){
    int connfd = ::accept(_sock.fd(),nullptr,nullptr);
    if(connfd == -1){
        perror("accept");
        return -1;
    }

    return connfd;
}

int Acceptor::fd() const{
    return _sock.fd();
}

void Acceptor::bind(){
    int ret = ::bind(_sock.fd(),
                     (struct sockaddr*)_addr.getInetAddressPtr(),
                     sizeof(struct sockaddr));
    if(ret == -1){
        perror("bind");
        return;
    }
}

void Acceptor::setReuseAddr(){
    int on = 1;
    //&on`：这个是一个布尔变量的引用，
    //通常设置为1，表示启用`SO_REUSEADDR`选项。
    //`sizeof(on)`：表示`on`变量的大小，用于指定选项值的长度。
    int ret = setsockopt(_sock.fd(),SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on));
    if(ret == -1){
        perror("setsockopt");
        return;
    }
}

void Acceptor::setReusePort(){
    int on = 1;
    int ret = setsockopt(_sock.fd(),SOL_SOCKET,SO_REUSEPORT,&on,sizeof(on));
    if(ret == -1){
        perror("setsockopt");
        return;
    }
}

void Acceptor::listen(){
    int ret = ::listen(_sock.fd(),128);
    if(ret == -1){
        perror("listen");
        return;
    }
}
